<!-- eslint-disable vue/no-template-shadow -->
<!--
 * @Description: 数据项管理页面
-->
<template>
  <!-- <BaseMainSlot>
    <template v-slot:treebox>
      <typeTree @treeselectvalue="treeselectvalue" />
    </template>
<template v-slot:searchbox>
      <SelectButton :buttonselectlist="buttonselectlist" @topitemtype="topitemtype" />
      <ActionBar :add-active="addActive" :del-active="delActive" :page-no="171" @add="add" @del="del" />
    </template>
<template v-slot:tablebox>
      <el-table ref="tableData" v-loading="loading" highlight-current-row :data="tableData" stripe border
        height="calc(100% - 50px)" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" :selectable="(row) => { return !row.selectable }" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="equipmentId" label="设备" min-width="120" />
        <el-table-column prop="dataItemName" label="数据项名称" min-width="120" />
        <el-table-column prop="dataType.mainingControlTypeStr" label="采控类型" />
        <el-table-column prop="dataType.unit" label="单位" />
        <el-table-column prop="dataType.visible" label="是否可展示">
          <template v-if="scoped.row.dataItemId" slot-scope="scoped">
            {{ scoped.row.visible ? '是' : '否' }}
          </template>
</el-table-column>
<el-table-column width="200" label="操作">
  <template v-if="scope.row.dataItemId" slot-scope="scope">
            <el-button class="text-btn-cursor" type="text" size="small" @click="edit(scope.row)">修改</el-button>
            <el-button v-if="judgePermission(171, 'delete')" class="text-btn-cursor cursor-delete" type="text"
              size="small" @click="handleDelete(scope.row.dataItemId)">删除</el-button>
          </template>
</el-table-column>
</el-table>
<Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize" @changePageSize="changePageSize"
  @changeCurrentPage="changeCurrentPage" />
<el-dialog :close-on-click-modal='false' :title="titleText + '数据项信息'" :visible.sync="dialogFormVisible" @close="cancel">
  <el-form ref="formData" label-position="left" :model="formData" :rules="rules" class="el-form">
    <el-form-item label="选择设备:" prop="equipmentId">
      <el-select filterable clearable v-model="formData.equipmentId" placeholder="请选择设备" filterable clearable>
        <el-option v-for="item in equipmentlist" :key="item.equipmentId" :label="item.equipmentName"
          :value="item.equipmentId" />
      </el-select>
    </el-form-item>
    <el-form-item label="数据项选择:" prop="iotDataItemId">
      <el-select filterable clearable v-model="formData.iotDataItemId" placeholder="请选择数据项" filterable clearable
        @change="depDataItem">
        <el-option v-for="item in dataItemList" :key="item.dataItemId" :label="item.dataItemName"
          :value="item.dataItemId" />
      </el-select>
    </el-form-item>
    <el-form-item label="是否可展示:" prop="visible">
      <el-select filterable clearable v-model="formData.visible" placeholder="请选择" filterable clearable>
        <el-option label="是" :value="true" />
        <el-option label="否" :value="false" />
      </el-select>
    </el-form-item>
    <el-form-item label="数据项名称:" prop="dataItemName">
      <el-input v-model="formData.dataItemName" placeholder="请输入数据项名称" filterable clearable>
      </el-input>
    </el-form-item>
  </el-form>
  <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
    <el-button class="cancelbtn" @click="cancel">取 消</el-button>
    <el-button class="savebtn" type="primary" @click="save('formData')">保 存</el-button>
  </div>
</el-dialog>
</template>
</BaseMainSlot> -->
  <div class="content">
    <div class="typeTree">
      <typeTree @treeselectvalue="treeselectvalue" />
    </div>
    <MainSlot>
      <template v-slot:btn>
        <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
      </template>
      <template v-slot:tab>
        <EnumSlot @handleEvent="getEnumEvent" :selectIndex="selectIndex" :enumList="buttonselectlist"
          :labelKey="'value'">
        </EnumSlot>
      </template>
      <template v-slot:table>
        <el-table ref="tableData" v-loading="loading" highlight-current-row :data="tableData" stripe border
          height="calc(100% - 50px)" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" :selectable="(row) => { return !row.selectable }" />
          <el-table-column type="index" label="序号" width="50" />
          <el-table-column prop="equipmentId" label="设备" min-width="120" />
          <el-table-column prop="dataItemName" label="数据项名称" min-width="120" />
          <el-table-column prop="dataType.mainingControlTypeStr" label="采控类型" />
          <el-table-column prop="dataType.unit" label="单位" />
          <el-table-column prop="dataType.visible" label="是否可展示">
            <template v-if="scoped.row.dataItemId" slot-scope="scoped">
              {{ scoped.row.visible ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column width="200" label="操作">
            <template v-if="scope.row.dataItemId" slot-scope="scope">
              <el-button class="text-btn-cursor" type="text" size="small" @click="edit(scope.row)">修改</el-button>
              <!-- <el-button v-if="judgePermission(171, 'edit')" class="text-btn-cursor" type="text" size="small" @click="edit(scope.row)">修改</el-button> -->
              <el-button v-if="judgePermission(171, 'delete')" class="text-btn-cursor cursor-delete" type="text"
                size="small" @click="handleDelete(scope.row.dataItemId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template v-slot:pagination>
        <Pagination @current-change="changeCurrentPage" :page="currentPage" :size="pageSize" :total="totalSize">
        </Pagination>
      </template>
      <template v-slot:dialogModule>
        <el-dialog :close-on-click-modal='false' :title="titleText + '数据项信息'" width="30%"
          :visible.sync="dialogFormVisible" @close="cancel">
          <el-form ref="formData" :model="formData" :rules="rules" label-width="120px" class="demo-ruleForm">
            <el-form-item label="选择设备:" prop="equipmentId">
              <el-select class="w100p" filterable clearable v-model="formData.equipmentId" placeholder="请选择设备">
                <el-option v-for="item in equipmentlist" :key="item.equipmentId" :label="item.equipmentName"
                  :value="item.equipmentId" />
              </el-select>
            </el-form-item>
            <el-form-item label="数据项选择:" prop="iotDataItemId">
              <el-select class="w100p" filterable clearable v-model="formData.iotDataItemId" placeholder="请选择数据项"
                @change="depDataItem">
                <el-option v-for="item in dataItemList" :key="item.dataItemId" :label="item.dataItemName"
                  :value="item.dataItemId" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否可展示:" prop="visible">
              <el-select class="w100p" filterable clearable v-model="formData.visible" placeholder="请选择">
                <el-option label="是" :value="true" />
                <el-option label="否" :value="false" />
              </el-select>
            </el-form-item>
            <el-form-item label="数据项名称:" prop="dataItemName">
              <el-input v-model="formData.dataItemName" placeholder="请输入数据项名称" filterable clearable>
              </el-input>
            </el-form-item>
          </el-form>
          <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
            <el-button class="cancelbtn" @click="cancel">取 消</el-button>
            <el-button class="savebtn" type="primary" @click="save('formData')">保 存</el-button>
          </div>
        </el-dialog>
      </template>
    </MainSlot>
  </div>
</template>

<script>


import MainSlot from "@/components-production-management/MainSlot";
import Pagination from '@/components-production-management/Pagination';
import BtnSlot from '@/components-production-management/BtnSlot';
import EnumSlot from '@/components-production-management/EnumSlot';

import DataItemManageApi from "@/api/basic-info-manage/data-item-manage";
import EnumApi from "@/api/enum";
import UnitManageApi from "@/api/basic-info-manage/unit-manage";
import DeviceManagementApi from "@/api/basic-info-manage/device-management";
import typeTree from "./components/trelist.vue";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";

export default {
  name: "dataItemManagement",
  components: {
    Pagination,
    typeTree,
    EnumSlot,
    BtnSlot,
    Pagination,
    MainSlot
  },
  mixins: [mymixin],
  data() {
    return {
      loading: false,
      btnList: ['add', 'delete'],
      selectIndex: 0,
      buttonselectlist: [
        { name: "COLLECTION", value: "采集" },
        { name: "CONTROL", value: "控制" },
        { name: "ACQUISITIONCONTROL", value: "采集控制" }
      ],
      dataItemList: [],
      unitList: [],
      rules: {
        equipmentId: [
          { required: true, message: "请选择设备", trigger: ["change", "blur"] }
        ],
        iotDataItemId: [
          { required: true, message: "请选择数据项", trigger: ["change", "blur"] }
        ],
        visible: [
          { required: true, message: "请选择是否可展示", trigger: ["change", "blur"] }
        ],
        dataItemName: [
          { required: true, message: "请输入数据项名称", trigger: ["change", "blur"] }
        ],
      },
      // 选中的设备id
      equipmentId: 1,
      // 搜索设备名称
      equipmentName: "",
      // 选中的鱼塘id数组 ID组成
      incomeCostIdList: [],
      dialogFormVisible: false,
      scope: "",
      topitemType: [],
      options: [],
      equipmentlist: [],
      formData: {
        dataType: {}
      }
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    dialogFormVisible(v) {
      if (v) {
        this.$nextTick(() => {
          this.$refs['formData'].clearValidate()
        })
      }
    }
  },
  created() {
    // 获取相关枚举类型
    this.queryEnum();
    // 获取当前基地所有数据项
    this.ownership();
    // 获取当前基地所有设备
    this.queryDeviceManagement();
    // 获取单位
    this.queryUnit();
  },
  mounted() { },
  methods: {

    getEnumEvent(enumInfo) {
      let { data, index } = enumInfo;
      this.topitemType = data.name;
      this.selectIndex = index;
      this.tableData = [];
      this.getTableDataList();
    },
    //获取选中Btn
    getBtnEvent(flag) {
      console.log(flag)
      if (flag == 'add') {
        this.add();
      } else if (flag == 'delete') {
        this.delmessage()
      }
    },
    // 查询枚举类型
    queryEnum() {
      EnumApi.list({ enumType: "MainingControlType" }).then(res => {
        if (res.success) {
          this.buttonselectlist = res.data;
          this.getEnumEvent({
            data: this.buttonselectlist[0],
            index: 0
          });
        }
      });
    },
    // 查询设备
    queryDeviceManagement(e) {
      DeviceManagementApi.queryByCondition({ equipmentName: e }).then(res => {
        this.equipmentlist = res.data;
      });
    },
    // 查询单位
    queryUnit() {
      UnitManageApi.queryByCondition().then(res => {
        this.unitList = res.data;
      });
    },
    // 查询当前基地数据项
    ownership(e) {
      DataItemManageApi.queryDataItemByCompanyMark().then(res => {
        let data = res.data;
        this.dataItemList = data;
      });
    },
    // 点击设备
    treeselectvalue(e) {
      this.equipmentId = e;
      this.getTableDataList();
    },
    // 获取表格数据
    getTableDataList() {
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          mainingControlTypeList: [this.topitemType],
          equipmentId: this.equipmentId
        }
      };
      this.loading = true;
      DataItemManageApi.queryPageByCondition(params).then(res => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.totalSize = data.totalElements;
          this.tableData = data.content;
        }
      }).catch(err => {
        this.loading = false;
      });
    },
    // 循环过滤树形数组
    filterArrForKey(arr) {
      let newArr = [];
      if (arr == []) {
        return;
      }
      newArr = arr.map(item => {
        if (item.child.length > 0) {
          item = {
            ...item,
            child: this.filterArrForKey(item.child)
          };
        } else {
          delete item.child;
        }
        return item;
      });
      newArr = newArr.filter(item => item != null);
      return newArr;
    },
    depDataItem(e) {
      let index = this.dataItemList.findIndex(b => b.dataItemId === e);
      let form = { ...this.dataItemList[index] };
      // 初始化datatype属性(这玩意莫名其妙地丢了)
      this.$set(this.formData, "dataType", {});
      // 赋值相关属性
      this.$set(this.formData, "iotDataItemId", form.dataItemId);
      this.$set(this.formData, "dataItemName", form.dataItemName);
      this.$set(this.formData, "dataTypeId", form.dataTypeId);
      this.$set(
        this.formData.dataType,
        "dataTypeName",
        form.dataType.dataTypeName
      );
      this.$set(
        this.formData.dataType,
        "mainingControlTypeValue",
        form.dataType.mainingControlType
      );
      this.$set(
        this.formData.dataType,
        "enumListType",
        form.dataType.enumListType
      );
      this.$set(this.formData.dataType, "valueType", form.dataType.valueType);
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    handleSelectionChange(list) {
      this.incomeCostIdList = [];
      this.incomeCostIdList = list.map(item => item.dataItemId);
      if (this.incomeCostIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      DataItemManageApi.delListById({ idList: this.incomeCostIdList }).then(
        res => {
          if (res.success) {
            this.$message.success("删除成功");
            this.getTableDataList();
          } else {
            this.$message.warning("删除失败");
          }
        }
      );
    },
    handleDelete(val) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",

      })
        .then(() => {
          DataItemManageApi.delById({ id: val }).then(res => {
            if (res.success) {
              this.$message.success("删除成功");
              this.getTableDataList();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            // 编辑接口
            DataItemManageApi.edit(this.formData).then(res => {
              if (res.success) {
                this.$message.success("修改成功！");
                this.cancel();
                this.getTableDataList();
              } else {
                this.$message.error("添加失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            DataItemManageApi.add(this.formData).then(res => {
              if (res.success) {
                this.$message.success("添加成功！");
                this.cancel();
                this.getTableDataList();
              } else if (res.success === false && res.errCode === 200) {
                this.$message.error(res.message);
              }
            });
          }
        }
      });
    },
    // 添加
    add() {
      this.nowChanceStau = "add";
      this.titleText = "添加";
      this.dialogFormVisible = true;
    },
    edit(row) {
      this.formData = { ...row };
      this.nowChanceStau = "edit";
      this.titleText = "修改";
      this.dialogFormVisible = true;
    }
  }
};
</script>

<style scoped lang="scss">
.content {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
  flex-wrap: nowrap;

  .typeTree {
    width: 300px;
  }
}

.main {
  width: calc(100% - 300px);

  ::v-deep .tableSlot {
    height: 100% !important;
  }
}
</style>
